package GUI;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;

import java.awt.Font;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.border.TitledBorder;
import javax.swing.UIManager;
import javax.swing.SwingConstants;

import model.Vehicle;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import control.VehicleCtrl;
import java.awt.Color;

public class vehicles extends JFrame {

	private final TableRowSorter<TableModel> sorter;
	private JPanel contentPane;
	private JTable vehTable;
	private JTextField tfLicensePlate;
	private JTextField tfType;
	private JTextField tfYear;
	private JTextField tfColor;
	private JTextField tfFactoryNumber;
	private VehicleCtrl vehicleCtrl = new VehicleCtrl();
	private static vehicleTable vehT = new vehicleTable();
	private JTextField tfSearch;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					vehicles frame = new vehicles();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public vehicles() {
		setTitle("VEHICLES");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 1050, 600);
		contentPane = new JPanel();
		contentPane.setBackground(new Color(255, 255, 153));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 82, 692, 470);
		contentPane.add(scrollPane);
		
		vehTable = new JTable();
		sorter = new TableRowSorter<TableModel>(vehT);
		vehTable.setRowSorter(sorter);
		scrollPane.setViewportView(vehTable);
		
		JPanel panel = new JPanel();
		panel.setBackground(new Color(255, 255, 153));
		panel.setLayout(null);
		panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Vehicle Control", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		panel.setBounds(712, 51, 312, 501);
		contentPane.add(panel);
		
		vehTable.addMouseListener(new MouseAdapter() {
      	  public void mouseClicked(MouseEvent e) {
      	    if (e.getClickCount() == 2) {
      	      JTable target = (JTable)e.getSource();
      	      int row = target.getSelectedRow();
      	      setVehicleFields((String)vehTable.getModel().getValueAt(row, 0));
      	    }
      	  }
      	});
		
		JLabel lblLicensePlate = new JLabel("License Plate :");
		lblLicensePlate.setHorizontalAlignment(SwingConstants.RIGHT);
		lblLicensePlate.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblLicensePlate.setBounds(6, 16, 114, 31);
		panel.add(lblLicensePlate);
		
		tfLicensePlate = new JTextField();
		tfLicensePlate.setColumns(10);
		tfLicensePlate.setBounds(130, 20, 170, 25);
		panel.add(tfLicensePlate);
		
		JLabel lblType = new JLabel("Type :");
		lblType.setHorizontalAlignment(SwingConstants.RIGHT);
		lblType.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblType.setBounds(6, 58, 114, 31);
		panel.add(lblType);
		
		JLabel lblYear = new JLabel("Year :");
		lblYear.setHorizontalAlignment(SwingConstants.RIGHT);
		lblYear.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblYear.setBounds(6, 100, 114, 31);
		panel.add(lblYear);
		
		tfType = new JTextField();
		tfType.setColumns(10);
		tfType.setBounds(130, 62, 170, 25);
		panel.add(tfType);
		
		tfYear = new JTextField();
		tfYear.setColumns(10);
		tfYear.setBounds(130, 104, 170, 25);
		panel.add(tfYear);
		
		JLabel lblColor = new JLabel("Color :");
		lblColor.setHorizontalAlignment(SwingConstants.RIGHT);
		lblColor.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblColor.setBounds(6, 142, 114, 31);
		panel.add(lblColor);
		
		JLabel lblFactoryNumber = new JLabel("Factory Number :");
		lblFactoryNumber.setHorizontalAlignment(SwingConstants.RIGHT);
		lblFactoryNumber.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblFactoryNumber.setBounds(6, 184, 114, 31);
		panel.add(lblFactoryNumber);
		
		tfColor = new JTextField();
		tfColor.setColumns(10);
		tfColor.setBounds(130, 146, 170, 25);
		panel.add(tfColor);
		
		tfFactoryNumber = new JTextField();
		tfFactoryNumber.setColumns(10);
		tfFactoryNumber.setBounds(130, 188, 170, 25);
		panel.add(tfFactoryNumber);
		
		JButton btnVadd = new JButton("Add");
		btnVadd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0)
			{
				if(ifEmpty()) return;
				if(ifVehicleExists())
				{
					JOptionPane.showMessageDialog(null,"Vehicle with this License Plate already exists.");
					return;
				}
				try
				{
					vehicleCtrl.createVehicle(tfLicensePlate.getText(), tfType.getText(), tfYear.getText(),
					tfColor.getText(), tfFactoryNumber.getText());
					updateVehicleTable();
					clearTextFields();
					JOptionPane.showMessageDialog(null,"Vehicle has been successfully created.");
				}
				catch (Exception r)
				{
					JOptionPane.showMessageDialog(null, "Error in creating Vehicle.");
				}
			}
		});
		btnVadd.setFont(new Font("Times New Roman", Font.BOLD, 17));
		btnVadd.setBounds(10, 459, 90, 31);
		panel.add(btnVadd);
		
		JButton btnVupdate = new JButton("Update");
		btnVupdate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0)
			{
				if(ifEmpty()) return;
				if(ifVehicleExists() == false)
				{
					JOptionPane.showMessageDialog(null,"Vehicle with this License Plate does not exists.");
					return;
				}
				try
				{
					vehicleCtrl.updateVehicle(tfLicensePlate.getText(), tfType.getText(), tfYear.getText(),
					tfColor.getText(), tfFactoryNumber.getText());
					updateVehicleTable();
					clearTextFields();
					JOptionPane.showMessageDialog(null,"Vehicle has been successfully updated.");
				}
				catch (Exception r)
				{
					JOptionPane.showMessageDialog(null, "Error in updating Vehicle.");
				}
			}
		});
		btnVupdate.setFont(new Font("Times New Roman", Font.BOLD, 17));
		btnVupdate.setBounds(110, 459, 90, 31);
		panel.add(btnVupdate);
		
		JButton btnVdelete = new JButton("Delete");
		btnVdelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				if(ifVehicleExists() == false)
				{
					JOptionPane.showMessageDialog(null,"Vehicle with this License Plate does not exists.");
					return;
				}
				try
				{
					if(vehicleCtrl.deleteVehicle(tfLicensePlate.getText()))
						JOptionPane.showMessageDialog(null,"Vehicle has been successfully deleted.");
                    else
                     	JOptionPane.showMessageDialog(null,"Cannot delete vehicle.");
					updateVehicleTable();
					clearTextFields();
				}
				catch(Exception r)
				{
					JOptionPane.showMessageDialog(null, "Error in deleting Vehicle");
				}
			}
		});
		btnVdelete.setFont(new Font("Times New Roman", Font.BOLD, 17));
		btnVdelete.setBounds(210, 459, 90, 31);
		panel.add(btnVdelete);
		
		JLabel lblListOfVehicles = new JLabel("LIST OF VEHICLES");
		lblListOfVehicles.setHorizontalAlignment(SwingConstants.CENTER);
		lblListOfVehicles.setFont(new Font("Times New Roman", Font.BOLD, 15));
		lblListOfVehicles.setBounds(10, 7, 673, 31);
		contentPane.add(lblListOfVehicles);
		
		JLabel lblManageVehicles = new JLabel("MANAGE VEHICLES");
		lblManageVehicles.setHorizontalAlignment(SwingConstants.CENTER);
		lblManageVehicles.setFont(new Font("Times New Roman", Font.BOLD, 15));
		lblManageVehicles.setBounds(693, 7, 312, 31);
		contentPane.add(lblManageVehicles);
		
		JLabel lblSearch = new JLabel("Search :");
		lblSearch.setBounds(10, 42, 110, 31);
		contentPane.add(lblSearch);
		lblSearch.setHorizontalAlignment(SwingConstants.RIGHT);
		lblSearch.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfSearch = new JTextField();
		tfSearch.setBounds(130, 45, 130, 25);
		contentPane.add(tfSearch);
		tfSearch.setColumns(10);
		tfSearch.getDocument().addDocumentListener(new DocumentListener() {  // <---
            @Override
            public void removeUpdate(DocumentEvent e) {
                filter();
            }
             
            @Override
            public void insertUpdate(DocumentEvent e) {
                filter();
            }
             
            @Override
            public void changedUpdate(DocumentEvent e) {}
        });
	}
	
	public void clearTextFields()
	{
		tfLicensePlate.setText("");
		tfType.setText("");
		tfYear.setText("");
		tfColor.setText("");
		tfFactoryNumber.setText("");
	}
	
	public boolean ifEmpty()
	{
		if(tfLicensePlate.getText().equals("") || tfType.getText().equals("") || tfYear.getText().equals("") ||
			tfColor.getText().equals("") || tfFactoryNumber.getText().equals(""))
		{
			JOptionPane.showMessageDialog(null,"Some of the fields are empty.");
			return true;
		}
		
		return false;
	}
	
	public boolean ifVehicleExists()
	{
		if(vehicleCtrl.getVehicleByLicensePlate(tfLicensePlate.getText()) != null)
			return true;
		return false;
	}
	
	public void updateVehicleTable()
	{
		vehT.setVeh(vehicleCtrl.getAllVehicles());
		vehTable.setModel(vehT);
	}
	
	public void setVehicleFields(String licensePlate)
    {
    	 Vehicle veh = vehicleCtrl.getVehicleByLicensePlate(licensePlate);
    	 tfLicensePlate.setText(veh.getLicensePlate());
         tfType.setText(veh.getType());
         tfYear.setText(veh.getYear());
         tfColor.setText(veh.getColor());
         tfFactoryNumber.setText(veh.getFactoryNr());
    }
	
	protected void filter()
	{
        sorter.setRowFilter(RowFilter.regexFilter("^(?i)"+tfSearch.getText()));
    }
}
